package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Employee;
import com.kaishengit.entity.Idea;
import com.kaishengit.entity.Ideacomment;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.Page;
import com.kaishengit.util.RowMapper;

public class IdeacommentDao {
	private DBHelp<Ideacomment> db = new DBHelp<Ideacomment>();

	public Page<Ideacomment> findCommentByIdeaId(String id, Page<Ideacomment> page) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT tic.employeeid,tic.ideaid,te.username,te.password,te.pic,te.email,tic.id,");
		sql.append("tic.content,tic.createtime FROM t_ideacomment AS tic LEFT JOIN t_employee AS te ");
		sql.append("ON te.id = tic.employeeid ");
		sql.append("WHERE ideaid = ? ORDER BY createtime DESC limit ?,?");
		List<Ideacomment> list = db.executeQueryForList(sql.toString(), new IdeacommentRowMapper(),id,page.getOffSet(),page.getPageSize());
		page.setResult(list);
		return page;
	}
	public List<Ideacomment> findCommentByIdeaId(String id) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT tic.employeeid,tic.ideaid,te.username,te.password,te.pic,te.email,tic.id,");
		sql.append("tic.content,tic.createtime FROM t_ideacomment AS tic LEFT JOIN t_employee AS te ");
		sql.append("ON te.id = tic.employeeid ");
		sql.append("WHERE ideaid = ?");
		return db.executeQueryForList(sql.toString(), new IdeacommentRowMapper(),id);
	}
	public boolean save(Ideacomment comment) {
		String sql = "insert into t_ideacomment(id,content,createtime,employeeid,ideaid) values(?,?,?,?,?)";
		return db.executeSQL(sql, comment.getId(),comment.getContent(),comment.getCreatetime(),comment.getEmployeeid(),comment.getIdeaid());
	}
	public Long getCount(String id){
		String sql = "select count(*) from t_ideacomment where ideaid = ?";
		return (Long) db.executeQueryForFunctions(sql, id);
	}
	
	private class IdeacommentRowMapper implements RowMapper<Ideacomment>{

		public Ideacomment mapRow(ResultSet rs) throws SQLException {
			Ideacomment ic = new Ideacomment();
			ic.setContent(rs.getString("content"));
			ic.setCreatetime(rs.getString("createtime"));
			ic.setEmployeeid(rs.getString("employeeid"));
			ic.setId(rs.getString("id"));
			ic.setIdeaid(rs.getString("ideaid"));
			Employee e = new Employee();
			e.setId(rs.getString("employeeid"));
			e.setEmail(rs.getString("email"));
			e.setPassword(rs.getString("password"));
			e.setPic(rs.getString("pic"));
			e.setUsername(rs.getString("username"));
			ic.setEmployee(e);
			return ic;
		}
		
	}


	
	
}
